<template>
  <div>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      @tree-load="treeLoadData"
    >
      <template slot="menuLeft">
        <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport">导入</el-button>
      </template>
      <template slot="menu" slot-scope="{ row, index }">
        <el-button type="text" size="small" icon="el-icon-plus" @click="handleAdd(row)">新建子仓库</el-button>
        <el-button type="text" size="small" icon="el-icon-edit" @click="$refs.crud.rowEdit(row, index)">编辑</el-button>
        <el-button type="text" size="small" icon="el-icon-delete" @click="$refs.crud.rowDel(row, index)">删除</el-button>
      </template>
    </avue-crud>
    <el-dialog append-to-body :close-on-click-modal="false" v-if="dialog.visible" :title="dialog.title" :visible.sync="dialog.visible" width="60%" top="5vh">
      <avue-form ref="form" class="workInfoForm" v-model="dialog.form" :option="dialog.option" @reset-change="handleReset" @submit="handleSubmit"> </avue-form>
      <div slot="footer" class="avue-dialog__footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="$refs.form.submit()">保存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="$refs.form.resetForm()">取消</el-button>
      </div>
    </el-dialog>
    <importDialogComp
      :title="importConfig.title"
      :url="importConfig.url"
      :export-name="importConfig.exportName"
      :visible.sync="importConfig.show"
      @submit="codeClose"
    ></importDialogComp>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import { delWarehouse, getWarehouseDetail, getWareHouseList, updateWarehouse } from '@/api/warehouse/warehouseManagement';
import importDialogComp from '@/components/dialog/import/index.vue';
import { remove } from '@/api/product/smtStandTable';
import { baseUrl } from '@/config/env';

export default {
  name: 'warehouseCurd',
  components: {
    importDialogComp
  },
  data() {
    return {
      importConfig: {
        title: '仓库导入',
        url: '/api/mes-warehouse/warehouse/importData',
        exportName: '仓库导入模板.xlsx',
        show: false
      },
      form: {},
      query: { isExpand: false, parentId: 0 },
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      data: [],
      option: {
        height: 'calc(100vh - 430px)',
        lazy: true,
        rowKey: 'id',
        rowParentKey: 'parentId',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: true,
        addBtnText: '新建仓库',
        indexLabel: '序号',
        columnBtn: false,
        menuWidth: 250,
        column: [
          {
            label: '仓库名称',
            prop: 'name',
            search: true,
            order: 1,
            searchOrder: 1,
            rules: [
              {
                required: true,
                message: '请输入仓库名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '仓库类型',
            prop: 'type',
            type: 'select',
            dicData: [
              { label: '委外仓', value: 'OUTSOURCING' },
              { label: '线边仓', value: 'LINE_SIDE' },
              { label: '原料仓', value: 'MATERIAL' },
              { label: '成品仓', value: 'PRODUCT' },
              { label: '报废仓', value: 'SCRAP' }
              // { label: '半成品仓', value: 'SEMIFINISHED' }
            ],
            searchOrder: 3,
            order: 3,
            search: true,
            rules: [{ required: true, message: '请选择仓库类型', trigger: 'change' }]
          },
          {
            label: '上级仓库',
            prop: 'parentId',
            hide: true,
            addDisplay: false,
            editDisplay: false
          },
          {
            label: '上级仓库',
            prop: 'parentName',
            hide: true,
            disabled: true,
            addDisplay: false,
            editDisplay: true
          },
          {
            label: '仓库编码',
            prop: 'code',
            searchOrder: 2,
            order: 2,
            search: true
          },
          {
            label: '仓库等级',
            prop: 'level',
            display: false,
            formatter: (val, value, label) => {
              return 'L' + value;
            }
          },
          {
            label: '状态',
            prop: 'status',
            type: 'switch',
            row: true,
            value: 1,
            dicData: [
              { label: '禁用', value: 2 },
              { label: '启用', value: 1 }
            ],
            rules: [{ required: true, message: '请选择状态' }]
          },
          {
            label: '更新人',
            prop: 'updateByName',
            display: false
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            display: false
          },
          {
            label: '备注',
            prop: 'remark',
            span: 24,
            overHidden: true,
            type: 'textarea'
          }
        ]
      },
      dialog: {
        visible: false,
        title: '新增子仓库',
        form: {},
        option: {
          submitBtn: false,
          emptyBtn: false,
          labelWidth: 100,
          column: [
            {
              label: '仓库名称',
              prop: 'name',
              rules: [
                {
                  required: true,
                  message: '请输入仓库名称',
                  trigger: 'blur'
                }
              ]
            },
            {
              label: '仓库编码',
              prop: 'code'
            },
            {
              label: '仓库类型',
              prop: 'type',
              type: 'select',
              disabled: true,
              dicData: [
                { label: '委外仓', value: 'OUTSOURCING' },
                { label: '线边仓', value: 'LINE_SIDE' },
                { label: '原料仓', value: 'MATERIAL' },
                { label: '成品仓', value: 'PRODUCT' }
              ],
              rules: [{ required: true, message: '请选择仓库类型', trigger: 'change' }]
            },
            {
              label: '上级仓库',
              prop: 'parentName',
              disabled: true
            },
            {
              label: '状态',
              prop: 'status',
              type: 'switch',
              row: true,
              value: 1,
              dicData: [
                { label: '禁用', value: 2 },
                { label: '启用', value: 1 }
              ],
              rules: [{ required: true, message: '请选择状态' }]
            },
            {
              label: '备注',
              prop: 'remark',
              span: 24,
              type: 'textarea'
            }
          ]
        }
      }
    };
  },
  async mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission, false),
        viewBtn: this.vaildData(this.permission, false),
        delBtn: this.vaildData(this.permission, false),
        editBtn: this.vaildData(this.permission, false)
      };
    }
  },
  methods: {
    handleAdd(row) {
      this.dialog.visible = true;
      this.dialog.title = '新增子仓库';
      this.dialog.form = structuredClone(row);
      this.dialog.form.parentId = row.id;
      this.dialog.form.parentName = row.name;
      this.dialog.form.type = row.type;
      this.dialog.form.name = '';
      this.dialog.form.code = '';
      this.dialog.form.id = '';
      this.dialog.form.remark = '';
    },
    async handleSubmit(form, done) {
      try {
        console.log(form, 'handleSubmit ');
        await updateWarehouse(form);
        this.dialog.visible = false;
        this.$message.success('新增成功');
        this.onLoad(this.page);
        done();
      } catch (e) {
        done();
        console.log(e);
      }
    },
    handleReset() {
      this.dialog.visible = false;
    },
    async rowSave(row, done, loading) {
      try {
        await updateWarehouse(row);
        this.$message.success('新增成功');
        this.onLoad(this.page);
        done();
      } catch (e) {
        loading();
      }
    },
    async rowUpdate(row, index, done, loading) {
      try {
        await updateWarehouse(row);
        this.$message.success('编辑成功');
        this.onLoad(this.page);
        done();
      } catch (e) {
        loading();
      }
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return delWarehouse(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    async beforeOpen(done, type) {
      if (type === 'edit') {
        const res = await getWarehouseDetail(this.form.id);
        const form = res.data.data;
        this.form = form;
        console.log(res.data.data);
      } else {
      }
      done();
    },
    searchReset() {
      this.query = {
        isExpand: false,
        parentId: 0
      };
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      let paramsLen = Object.keys(params).length;
      // 搜索
      if (paramsLen > 0) {
        params.isExpand = true;
      } else {
        // 刷新
        params.isExpand = false;
        params.parentId = 0;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      try {
        const res = await getWareHouseList(page.currentPage, page.pageSize, Object.assign(params, this.query, {}));
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records.map((item) => {
          return {
            ...item,
            hasChildren: item.hasChild
          };
        });
        this.loading = false;
        this.$refs.crud.refreshTable();
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    treeLoadData(tree, treeNode, resolve) {
      getWareHouseList(1, 10000, { parentId: tree.id }).then((res) => {
        const data = res.data.data && res.data.data.records;
        if (Array.isArray(data)) {
          data.forEach((item) => {
            if (item.hasChild) {
              item.hasChildren = true;
            }
          });
        }
        resolve(data || []);
      });
    },
    async codeClose() {
      this.onLoad(this.page);
    },
    handleImport() {
      this.importConfig.show = true;
    }
  }
};
</script>
<style lang="scss" scoped></style>
